package com.jfunit.java.helper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.sql.DataSource;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfunit.java.ConfigConstant;
import com.jfunit.java.util.PropsUtil;


/**
 * 数据库操作助手类
 * @author Administrator
 *
 */
public final class DatabaseHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
    
    //用于存放当前线程的sql链接对像
    private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<Connection>();
    private static final QueryRunner QUERY_RUNNER = new QueryRunner();//查询更新助手
    private static final BasicDataSource BASIC_DATA_SOURCE;//用于dbcp链接池的数据源
    
    static{
        //Properties props = PropsUtil.loadProps(ConfigConstant.CONFIG_FILE);
        Properties props = ConfigHelper.getProperties();
        String driverclassname = PropsUtil.getString(props,ConfigConstant.JDBC_DRIVER);
        String url = PropsUtil.getString(props,ConfigConstant.JDBC_URL);
        String username = PropsUtil.getString(props,ConfigConstant.JDBC_UERNAME);
        String password = PropsUtil.getString(props,ConfigConstant.JDBC_PASSWORD);
        
        BASIC_DATA_SOURCE = new BasicDataSource();
        BASIC_DATA_SOURCE.setDriverClassName(driverclassname);
        BASIC_DATA_SOURCE.setUrl(url);
        BASIC_DATA_SOURCE.setUsername(username);
        BASIC_DATA_SOURCE.setPassword(password);
    }
    
    public static DataSource getDataSource(){
        return BASIC_DATA_SOURCE;
    }
    
    public static QueryRunner getQueryRunner(){
        return QUERY_RUNNER;
    }
    /** 获取链接**/
    public static Connection getConnection(){
        Connection conn = CONNECTION_HOLDER.get();
        if (conn==null) {
            try {
                conn = BASIC_DATA_SOURCE.getConnection();
            } catch (Exception e) {
                LOGGER.error("get connection failure",e);
                throw new RuntimeException(e);
            }finally{
                CONNECTION_HOLDER.set(conn);
            }
        }
        return conn;
    }
    
    public static void closeConnection() {
        Connection conn = CONNECTION_HOLDER.get();
        if (conn!=null) {
            try {
                conn.close();
            } catch (Exception e) {
                LOGGER.error("close connection failure",e);
                throw new RuntimeException(e);
            }finally{
                CONNECTION_HOLDER.remove();
            }
        }
    }
    
    public static void closeRes(PreparedStatement ps){
        try {
            if(ps!=null){
               ps.close();
            }                
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void closeRes(PreparedStatement ps,ResultSet rs){
        try {
            if(rs!=null){
               rs.close();
            }
            if(ps!=null){
               ps.close();
            }        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 查询列表
     * @param entityClass
     * @param sql
     * @param params
     * @return
     */
    public static <T> List<T> queryEntityList(Class<T> entityClass,String sql,Object...params){
        List<T> result = null;
        try {
            result = QUERY_RUNNER.query(getConnection(),sql,new BeanListHandler<T>(entityClass),params);
        } catch (Exception e) {
            LOGGER.error("query list failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }
    
    /**
     * 查询单个实体
     * @param entityClass
     * @param sql
     * @param params
     * @return
     */
    public static <T> T queryEntity(Class<T> entityClass,String sql,Object...params){
        T result = null;
        try {
            result = QUERY_RUNNER.query(getConnection(), sql, new BeanHandler<T>(entityClass),params);
        } catch (Exception e) {
            LOGGER.error("query entity failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }
    
    /**
     * 执行多表链接查询语句
     * @param sql
     * @param params
     * @return
     */
    public static List<Map<String, Object>> executorQuery(String sql,Object...params){
        List<Map<String, Object>> result = null;
        try {
            result = QUERY_RUNNER.query(getConnection(), sql, new MapListHandler(),params);
        } catch (Exception e) {
            LOGGER.error("executor query failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }
    
    /**
     * 更新实体
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql,Object...params){
        int rows=0;
        try {
            rows = QUERY_RUNNER.update(getConnection(), sql,params);
        } catch (Exception e) {
            LOGGER.error("executor update failure",e);
            throw new RuntimeException(e);
        }
        return rows;
    }
    
    public static <T> boolean insertEntiry(Class<T> entityClass,Map<String, Object> fieldMap){
        if (MapUtils.isEmpty(fieldMap)) {
            LOGGER.error("can not insert entity: fieldMap is empty");
            return false;
        }
        
        String sql = "INSERT INTO "+getTableName(entityClass);
        StringBuilder columns  = new StringBuilder("(");
        StringBuilder values = new StringBuilder("(");
        
        for (String fieldName : fieldMap.keySet()) {
            columns.append(fieldName).append(",");
            values.append("?,");
        }
        
        columns.replace(columns.lastIndexOf(","), columns.length(), ")");
        values.replace(values.lastIndexOf(","), values.length(), ")");
        
        sql += columns+" VALUES "+values;
        
        Object[] params = fieldMap.values().toArray();
        return executeUpdate(sql, params) == 1;
        
    }
    
    /**
     * 更新实体
     * @param entityClass
     * @param id
     * @param fieldMap
     * @return
     */
    public static <T> boolean updateEntity(Class<T> entityClass,long id,Map<String, Object> fieldMap){
        if (MapUtils.isEmpty(fieldMap)) {
            LOGGER.error("can not update entity: fieldMap is empty");
            return false;
        }
        
        String sql = "update "+getTableName(entityClass) +" SET ";
        StringBuilder columns  = new StringBuilder();
        
        for (String fieldName : fieldMap.keySet()) {
            columns.append(fieldName).append("=?,");
        }
        
        sql += columns.substring(0, columns.lastIndexOf(",")) + " WHERE id = ?";
        
        List<Object> paramList = new ArrayList<Object>();
        paramList.addAll(fieldMap.values());
        paramList.add(id);
        Object[] params = paramList.toArray();
        return executeUpdate(sql, params) == 1;
    }
    
    public static <T> Boolean deleteEntity(Class<T> entityClass,long id){
        String sql  = "DELETE FROM "+getTableName(entityClass)+" WHERE id=?";
        return executeUpdate(sql,id) == 1;
    }
    
    //返回 表名.实体名称 全大写
    public static <T> String getTableName(Class<T> entityClass){
        return entityClass.getSimpleName().toUpperCase();
    }
    
    public static <T> T queryColumn(String sql,Object...params){
        T obj;
        try {
            obj = QUERY_RUNNER.query(getConnection(), sql,new ScalarHandler<T>(),params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return obj;
    }
    
    public static <T> Set<T> queryColumnSet(String sql,Object...params){
        Set<T> result = null;
        try {
            List<T> query = QUERY_RUNNER.query(getConnection(), sql,new ColumnListHandler<T>(),params);
            result = new HashSet<T>();
            result.addAll(query);
        } catch (Exception e) {
            LOGGER.error("query columnSet failure",e);
            throw new RuntimeException(e);
        }
        return result;
    }
    
    /**
     * 开启事务
     */
    public static void beginTransaction(){
        Connection conn = getConnection();
        if (conn!=null) {
            try {
                conn.setAutoCommit(false);//关闭自动提交，每次操作数据库都需要手动的提交（也就是开启了事务）
            } catch (Exception e) {
                LOGGER.error("begin transaction failure",e);
                throw new RuntimeException(e);
            }finally{
                CONNECTION_HOLDER.set(conn);
            }
        }
    }
    
    /**
     * 提交事务
     */
    public static void commitTransaction(){
        Connection conn = getConnection();
        if (conn!=null) {
            try {
                conn.commit();
                conn.close();
            } catch (Exception e) {
                LOGGER.error("commit transaction failure",e);
                throw new RuntimeException(e);
            }finally{
                CONNECTION_HOLDER.remove();//移除链接
            }
        }
    }
    
    public static void rollbackTransaction(){
        Connection conn = getConnection();
        if (conn!=null) {
            try {
                conn.rollback();
                conn.close();
            } catch (Exception e) {
                LOGGER.error("rollback transaction failure",e);
                throw new RuntimeException(e);
            }finally{
                CONNECTION_HOLDER.remove();
            }
        }
    }

}
